import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '../store'
import axios from "axios"
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    // 路由懒加载
    component: () => import( '../views/Home.vue'),
    children: [
      {
        path: '/index',
        name: 'Index',
        component: () => import( '../views/Index.vue')
      },
      {
        path: '/sys/usercenter',
        name: 'UserCenter',
        component: () => import( '../views/sys/UserCenter')
      },
   /*   {
        path: '/sys/role',
        name: 'Role',
        component: () => import( '@/views/sys/Role')
      },
      {
        path: '/sys/user',
        name: 'User',
        component: () => import( '@/views/sys/User')
      },
      {
        path: '/sys/menu',
        name: 'menu',
        component: () => import( '@/views/sys/Menu')
      }  */
    ]
  },

  {
    path: '/login',
    name: 'Login',
    component: () => import( '../views/Login.vue')
  }
]

const router = new VueRouter({
  mode:'history',
  routes
})

router.beforeEach((to, from, next) => {

  if(to.name !== "Login") {
 
    let hasRoute = store.state.menus.hasRoute;
    if(!hasRoute) {
      axios.get("/sys/menu/nav", {
        headers: {
          authorization: localStorage.getItem("token")
        }
      }).then(res => {
         let menus = res.data.data.nav;
         store.commit("SET_MENUSLIST", menus)
         store.commit("SET_PERMSLIST", res.data.data.authoritys)
    
         // 动态绑定路由
         let newRouters = router.options.routes;
        
         menus.forEach(menu => {
           if(menu.children) {
              menu.children.forEach(e => {
                let route = menuToRoute(e)
                newRouters[0].children.push(route)
              })
           }
           router.addRoutes(newRouters)
         }) 
      }) 
      hasRoute = true;
      store.commit("SET_HASROUTE", hasRoute)
    }
  }
 
  next()
}) 

const menuToRoute = (menu) => {
  if(!menu.component) {
    return null
  }
  let route = {
    path: menu.path,
    name: menu.name,
    meta: {
      title: menu.title,
      icon: menu.icon
    }
  } 
  route.component = () => import("@/views/" + menu.component + '.vue')
  return route
}
export default router
